#include <iostream>
#include <map>
#include <string>
#include <ctime>

using namespace std;

typedef struct mTapInfo{
	int tap_fd;
	long expire_time;

} TapInfo;

map<string, mTapInfo> mac_table;


mTapInfo getTap(string src_mac);
void addItem(string src_mac, int fd);
void deleteItem(string src_mac);
void showAllItems();
bool isValid(TapInfo tap_info);


/*
int main(){
	int flag = 1;
	while(flag){

		cout << "[1] add" << endl;
		cout << "[2] show" << endl;
		cout << "[3] del" << endl;
		cout << "[4] find" << endl;
		
		int choice;
		string key;
		int fd;
		TapInfo tap_info;

		cin >> choice;
		switch(choice){
			case 1:
				cout << "enter the key and fd " << endl;				
				cin >> key >> fd;
				addItem(key, fd);
				break;
			case 2:
				showAllItems();
				break;
			case 3:
				cout << "enter the key " << endl;
				cin >> key;
				deleteItem(key);
				break;
			case 4:
				// todo
				cout << "enter the key " << endl;
				cin >> key;
				tap_info = getTap(key);				
				cout << key << "\t\t" << tap_info.tap_fd << "\t\t" << tap_info.expire_time << endl;				
				break;
			default:
				flag = 0;
				continue;
		}
	
	}
}
*/


/**
 * add/update a item to hashtable
 */
void addItem(string src_mac, int fd){
	TapInfo tap_info;
	tap_info.tap_fd = fd;
	tap_info.expire_time = time(0)/3600 + 24*7;

	//mac_table.insert(std::pair<std::string, TapInfo>(src_mac, tap_info));
	mac_table[src_mac] = tap_info;
}


/**
 * get the TapInfo by src_mac
 */
TapInfo getTap(string src_mac){
	map<string, TapInfo>::iterator it = mac_table.find(src_mac);
	if(it != mac_table.end()){
		//cout << "find the des" << endl;
		if(isValid(mac_table.at(src_mac))){
			return mac_table.at(src_mac);		
		}	
	}
	TapInfo tap_info;
	tap_info.tap_fd = -1;
	return tap_info;
}

/**
 * delete item by src_mac
 */
void deleteItem(string src_mac){
	map<string, TapInfo>::iterator it = mac_table.find(src_mac);
	if(it != mac_table.end()){
		mac_table.erase(src_mac);	
	}
}

/**
 * show all items
 */
void showAllItems(){
	map<string, TapInfo>::iterator begin = mac_table.begin();
	map<string, TapInfo>::iterator end = mac_table.end();
	cout << "---------------------------hash entry-----------------------------" << endl;
	cout << "src_mac\t\t\t\t" << "tap\t\t" << "expire_time" << endl;	
	cout << "------------------------------------------------------------------" << endl;
	for(; begin != end; begin++){
		cout << (*begin).first << "\t\t" << (*begin).second.tap_fd << "\t\t" << (*begin).second.expire_time << endl;
	}
	cout << endl;
}

/**
 * is item expired ?
 */
bool isValid(TapInfo tap_info){
	// get now time(hour)
	long now = time(0)/3600;
	long expire = tap_info.expire_time;
	if(now >= expire){
		return false;
	}
	return true;
}
